package com.ruoyi.system.service.impl;

import com.ruoyi.system.service.IDeliveryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.*;

@Service
public class NotificationService {
    @Resource
    private IDeliveryService deliveryService;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 保存每个通知任务的ScheduledFuture，使用通知ID作为键
    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();

    public void scheduleNotification(LocalDateTime notificationTime, Long projectId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 计算从当前时间到通知时间的秒数差
        long delayInSeconds = ChronoUnit.SECONDS.between(now, notificationTime);

        if (delayInSeconds > 0) {
            // 任务调度：延迟到指定的通知时间执行
            ScheduledFuture<?> scheduledTask = scheduler.schedule(() -> sendNotification(projectId), delayInSeconds, TimeUnit.SECONDS);
            // 将ScheduledFuture与通知ID关联
            scheduledTasks.put(projectId, scheduledTask);
        } else {
            // 如果通知时间已过，立即执行任务
            sendNotification(projectId);
            scheduledTasks.remove(projectId);
        }
    }

    // 取消指定ID的调度任务
    public boolean cancelNotification(Long projectId) {
        // 获取对应的ScheduledFuture
        ScheduledFuture<?> scheduledTask = scheduledTasks.get(projectId);
        if (scheduledTask != null) {
            // 尝试取消任务
            boolean cancelled = scheduledTask.cancel(false);
            if (cancelled) {
                scheduledTasks.remove(projectId); // 任务取消成功后，移除记录
            }
            return cancelled;
        }
        return false; // 没有找到对应的任务
    }

    private void sendNotification(Long projectId) {
        // 你的发送消息逻辑
//        System.out.println("Notification sent at: " + LocalDateTime.now() + ",logId: " + logId);
        deliveryService.projectEnd(projectId);

    }

}
